package com.zrt.pad.login;

import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;

import com.zrt.pad.commonui.SharedApplication;
import com.zrt.pad.constfields.ConstFielsdes;
import com.zrt.pad.datasource.DataSourceInstance;
import com.zrt.pad.datasource.bean.UsrUser;
import com.zrt.pad.util.Chinese;
import com.zrt.pad.util.DESUtil;
import com.zrt.pad.util.SellUtil;

public class Login {
	
	private String userCode = "";
	private String userName = "";
	
	public boolean isLogin = false;
	
	public boolean isLogin() {
		boolean islogin = false;
		SharedPreferences user = SharedApplication.context.getSharedPreferences("user", Context.MODE_PRIVATE);
		if(user != null) {
			this.userCode = user.getString("userCode", "");
			this.userName = user.getString("userNmae", "");
			ConstFielsdes.userCode = this.userCode;
			ConstFielsdes.username = this.userName;
			
			if( !userCode.equals("") || !userName.equals("") ) {
				islogin = true;
			}
		}
		this.isLogin = islogin;
		
		return islogin;
	}
	
	public String login(String usercode,String password) {
		String result = "登录成功";
		DataSourceInstance dsinst = new DataSourceInstance();
		List<UsrUser> lsUsrUserTable = dsinst.queryUsrUser();
		for(UsrUser user : lsUsrUserTable ) {
			if(user.getUsercode().equals(usercode)) {
				String spasswordtmp = DESUtil.instance.getEncString(password).trim();
				String stmp = user.getPasswd().trim();
				if(stmp.equals(spasswordtmp)) {
					this.userCode = user.getUsercode();
					this.userName = Chinese.toChinese(user.getUsername());
					ConstFielsdes.userCode = this.userCode;
					ConstFielsdes.username = this.userName;
					
					SellUtil.saveUserLoginInfo(ConstFielsdes.userCode, password);
					SharedPreferences.Editor userEdit = SharedApplication.context.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
					userEdit.putString("userCode", this.userCode);
					userEdit.putString("userNmae", this.userName);
					userEdit.putString("password", password);
					userEdit.commit();
					
					break;
				} else {
					result = "密码错误";
					break;
				}
			}else {
				result = "用户不存在";
				break;
			}
		}
		return result;
	}
	
	public void logout() {
		SharedPreferences.Editor userEdit = SharedApplication.context.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
		userEdit.clear();
		userEdit.commit();
	}

	public String getUserCode() {
		return userCode;
	}

	public String getUserName() {
		return userName;
	}
	
}
